package com.hyt.it.ogt.controller.ykcj.zs;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.common.config.ApiVersionConstant;
import com.hyt.it.ogt.controller.base.BaseController;
import com.hyt.it.ogt.ykcj.common.enums.zs.VariableCodeEnums;
import com.hyt.it.ogt.ykcj.domain.vo.ZsTemplateVo;
import com.hyt.it.ogt.ykcj.domain.zs.ZsTemplate;
import com.hyt.it.ogt.ykcj.domain.zs.ZsTemplateConfig;
import com.hyt.it.ogt.ykcj.domain.zs.dto.ImageBaseDTO;
import com.hyt.it.ogt.ykcj.service.system.IFileUpHwCloudService;
import com.hyt.it.ogt.ykcj.service.zs.IZsTemplateConfigService;
import com.hyt.it.ogt.ykcj.service.zs.IZsTemplateService;
import com.hyt.it.ogt.ykcj.service.zs.impl.ZsExamineeInfoServiceImpl;
import com.hyt.it.ogt.ykcj.utils.ImageMarkUtils;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.service.IBaseLoginService;
import com.hyt.model.PageParam;
import com.hyt.swagger.ApiVersion;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Set;

/**
 * @program: it-ogt-ykcj
 * @description: 模板控制器
 * @author: Yang HuanKun
 * @create: 2022-06-21 10:18
 **/
@Api(tags = "zs.1.模板管理", value = "模板控制器")
@ApiSort(value = 401)
@RestController
@RequestMapping("/template")
public class TemplateController extends BaseController {
	
	@Autowired
    private IBaseLoginService baseLoginService;

    @Resource
    private IZsTemplateService templateService;
    
    @Resource
    private IZsTemplateConfigService templateConfigService;
    
    @Resource
    private ZsExamineeInfoServiceImpl examineesInfoService;
    
    @Resource
    private IFileUpHwCloudService fileUpHwCloudService;
    
    
    @ApiOperation(value = "41.1.1 分页查询模板信息",  notes = "20000:成功;52411101: 获取不到当前登录人信息")
    @ApiOperationSort(value = 1)
    @ApiImplicitParams({
		@ApiImplicitParam(
			name = "templateName", value = "模板名称", dataType = "string", paramType = "query"
		),
		@ApiImplicitParam(
				name = "pageSize", value = "分页查询每页条数", dataType = "string", paramType = "query"
		),
		@ApiImplicitParam(
				name = "pageNum", value = "分页查询当前页码", dataType = "string", paramType = "query"
		)
	})
    @ApiVersion(group = ApiVersionConstant.V2_4_2)
    @GetMapping("/get/page")
    public ApiResponse<Page<ZsTemplateVo>> getPage(String templateName) {
    	logger.info("## getzstemplatePage templateName:{}", templateName);
    	
    	// 获取当前登录人用户信息
    	User user = baseLoginService.getSysUser();
        if(null == user || StringUtils.isEmpty(user.getId())) {
        	return ApiResponse.<Page<ZsTemplateVo>> builder().code(52411101).build();
        }
		Set<String> deptIds = baseLoginService.getDeptIds();
		startPage();
    	PageParam<ZsTemplateVo> pageParam = new PageParam<ZsTemplateVo>();
    	pageParam = templateService.getTemplateInfoByPage(pageParam, templateName, user.getOfficeid(), deptIds);
    	return ApiResponse.<Page<ZsTemplateVo>> builder().code(20000).data(pageParam).build();
    }
    
    
    
	@ApiOperation(value = "41.1.2 根据查询数量查询模板信息", notes = "20000:成功;52411201: 获取不到当前登录人信息, 52411202: 查询数量过大")
	@ApiOperationSort(value = 1)
	@ApiImplicitParams({ @ApiImplicitParam(name = "querySize", value = "查询条数", dataType = "Integer", paramType = "query") })
	@ApiVersion(group = ApiVersionConstant.V2_4_2)
	@GetMapping("/queryList")
	public ApiResponse<List<ZsTemplateVo>> getZsTemplateVoList(Integer querySize) {
		logger.info("## getZsTemplateVoList querySize:{}", querySize);

		// 获取当前登录人用户信息
		User user = baseLoginService.getSysUser();
		if (null == user || StringUtils.isEmpty(user.getId())) {
			return ApiResponse.<List<ZsTemplateVo>> builder().code(52411201).build();
		}
		if (null == querySize || querySize == 0) {
			querySize = ZsTemplateVo.DEFAULTLISTSIZE;
		}
		if (querySize > 1000) {
			return ApiResponse.<List<ZsTemplateVo>> builder().code(52411202).build();
		}
		List<ZsTemplateVo> zsTemplateVos = templateService.getTemplateListBySize(user.getOfficeid(), querySize);
		return ApiResponse.<List<ZsTemplateVo>> builder().code(20000).data(zsTemplateVos).build();
	}
	
	
	
	@ApiOperation(value = "41.1.3 根据证书模板id创建证书模板数据", notes = "20000:成功;52411301: 获取不到当前登录人信息")
	@ApiOperationSort(value = 3)
	@ApiImplicitParams(
			{ 
				@ApiImplicitParam(name = "templateId", value = "模板id", dataType = "String", paramType = "query", required = true) 
			}
	)
	@ApiVersion(group = ApiVersionConstant.V2_4_2)
	@GetMapping("/generateTemplate")
	public ApiResponse<String> generateTemplate(String templateId) {
		logger.info("## generateTemplate templateId:{}", templateId);
		// 获取当前登录人用户信息
		User user = baseLoginService.getSysUser();
		if (null == user || StringUtils.isEmpty(user.getId())) {
			return ApiResponse.<String> builder().code(52411301).build();
		}
		ZsTemplate template = templateService.getById(templateId);
        List<ZsTemplateConfig> zsTemplateConfigs = templateConfigService.listAllConfigByTemplate(templateId);
        zsTemplateConfigs.forEach(data -> {
            if (data.getVariableCode().equals(VariableCodeEnums.NAME.getCode())) {
                String variableDefaultValue = data.getVariableDefaultValue();
                if (StrUtil.length(variableDefaultValue) == 2) {
                    variableDefaultValue = new StringBuilder(variableDefaultValue)
                            .insert(1, new char[]{StrPool.C_SPACE, StrPool.C_SPACE}, 0, 2)
                            .toString();
                    data.setVariableDefaultValue(variableDefaultValue);
                }
            }
        });
        List<ImageBaseDTO> imageBaseDTOS = examineesInfoService.assembleImageBaseDTO(zsTemplateConfigs);
        File file = ImageMarkUtils.writeImage(template.getTemplateUrl(), imageBaseDTOS);
        String fileName = UUIDUtils.newSortUUID().substring(0, 12) + ".png";
        String templateUrl = fileUpHwCloudService.uploadFileToHuawei(file, "template", fileName);
        logger.info("## generateTemplate templateId:{}", templateId);
        return ApiResponse.<String> builder().code(20000).data(templateUrl).build();
	}
}
